package com.example.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author benjamin_5
 * @Description
 * @date 2023/2/16
 */
@Configuration
public class RateLimitConfig {

    /**
     * 通过IP限流
     * 返回值Mono<String> 泛型中的String 就代表令牌分给谁
     */
    @Bean
    public KeyResolver ipKeyResolver(){
        return new KeyResolver() {
            @Override
            public Mono<String> resolve(ServerWebExchange exchange) {
                String hostName = exchange.getRequest().getRemoteAddress().getHostName();
                System.out.println("ip: "+hostName);
                return Mono.just(hostName);
            }
        };
    }

    /**
     * 通过用户限流
     * 请求路径中要包含userId参数，用于标识用户
     */
//    @Bean
    public KeyResolver userKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("userId"));
    }

    /**
     * 通过接口限流
     * 请求地址路径作为限流的key
     */
//    @Bean
    public KeyResolver apiKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getPath().value());
    }
}
